import datetime
import time
from json import JSONDecodeError
import pymssql
import requests
from Save_database import Save_database
import json


class getCommentSummaries(object):
    def __init__(self):
        self.db = pymssql.connect(host='192.168.0.186', user='sa', password='987987abc#', port='1433',
                                  database='Crawler.Paterson', charset="utf8")
        self.cursor = self.db.cursor()
        self.sd = Save_database(self.db)

    def is_save_comment(self):
        Flag = True
        try:
            sql = 'select Quession_id from Paterson_Answer'
            self.cursor.execute(sql)
            self.cursor.fetchall()
            Flag = False
        except Exception:
            Flag = True
        finally:
            return Flag

    def get_current_week(self):
        monday, sunday = datetime.date.today(), datetime.date.today()
        one_day = datetime.timedelta(days=1)
        while monday.weekday() != 0:
            monday -= one_day
        while sunday.weekday() != 6:
            sunday += one_day
        week = str(monday)+str('/')+str(sunday)
        return week

    def getSkuForQuestion(self):
        sql = 'SELECT sku from Paterson_Product_List where sku not in (select sku from Paterson_Answer where Update_week = %s) and update_week = %s'
        self.cursor.execute(sql, (self.get_current_week(), self.get_current_week()))
        data = self.cursor.fetchall()
        return data

    def parse_CommentSummaries(self, sku):
        url = 'https://question.jd.com/question/getQuestionAnswerList.action?&page=1&productId='+str(sku)
        r = requests.get(url)
        print('开始')
        time.sleep(1)
        try:
            jsCode = json.loads(r.text, encoding='utf-8')
            isQuession = jsCode.get('totalItem')
            if isQuession != 0:
                pageNum = int(isQuession/10)+1
                if pageNum >= 2:
                    for i in range(1, pageNum+1):
                        url = 'https://question.jd.com/question/getQuestionAnswerList.action?&page={}&productId={}'.format(pageNum, sku)
                        r = requests.get(url)
                        time.sleep(1)
                        quessionNum = len(jsCode.get('questionList'))
                        for i1 in range(0, quessionNum):
                            quesion = jsCode.get('questionList')[i1].get('content')
                            quession_id = jsCode.get('questionList')[i].get('id')
                            answerNum = len(jsCode.get('questionList')[i1].get('answerList'))
                            if answerNum >= 1:
                                for ii in range(0, answerNum):
                                    id = jsCode.get('questionList')[i1].get('answerList')[ii].get('productId')
                                    answer = jsCode.get('questionList')[i1].get('answerList')[ii].get('content')
                                    answer_create_date = jsCode.get('questionList')[i1].get('answerList')[ii].get(
                                        'created')
                                    answer_modified_date = jsCode.get('questionList')[i1].get('answerList')[ii].get(
                                        'modified')
                                    answer_user = jsCode.get('questionList')[i1].get('answerList')[ii].get(
                                        'userInfo').get('nickName')
                                    if self.is_save_comment():
                                        self.sd.save_quession_data(sku, quesion, answer, answer_create_date, answer_modified_date, answer_user, self.get_current_week(), quession_id)
                            else:
                                if self.is_save_comment():
                                    self.sd.save_quession_data(sku, quesion, '', '', '', '', self.get_current_week(), quession_id)
                elif pageNum == 1:
                    quessionNum = len(jsCode.get('questionList'))
                    for i in range(0, quessionNum):
                        quesion = jsCode.get('questionList')[i].get('content')
                        quession_id = jsCode.get('questionList')[i].get('id')
                        answerNum = len(jsCode.get('questionList')[i].get('answerList'))
                        if answerNum >= 1:
                            for ii in range(0, answerNum):
                                productId = jsCode.get('questionList')[i].get('answerList')[ii].get('productId')
                                answer = jsCode.get('questionList')[i].get('answerList')[ii].get('content')
                                answer_create_date = jsCode.get('questionList')[i].get('answerList')[ii].get('created')
                                answer_modified_date = jsCode.get('questionList')[i].get('answerList')[ii].get('modified')
                                answer_user = jsCode.get('questionList')[i].get('answerList')[ii].get('userInfo').get('nickName')
                                if self.is_save_comment():
                                    self.sd.save_quession_data(sku, quesion, answer, answer_create_date, answer_modified_date, answer_user, self.get_current_week(), quession_id)
                        else:
                            if self.is_save_comment():
                                self.sd.save_quession_data(sku, quesion, '', '', '', '', self.get_current_week(), quession_id)
        except JSONDecodeError as e:
            print(e)

    def Main(self):
        data = self.getSkuForQuestion()
        # gc.parse_QuestionAnswerList(1)
        for i in data:
            gc.parse_CommentSummaries(i[0])


if __name__ == '__main__':
    gc = getCommentSummaries()
    gc.Main()


